package com.atguigu.gulimall.cart.service.Impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.cart.feign.ProductFeignService;
import com.atguigu.gulimall.cart.interceptor.CartInterceptor;
import com.atguigu.gulimall.cart.service.CartService;
import com.atguigu.gulimall.cart.to.UserInfoTo;
import com.atguigu.gulimall.cart.vo.Cart;
import com.atguigu.gulimall.cart.vo.CartItem;
import com.atguigu.gulimall.cart.vo.SkuInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

/**
 * @author 孤风雪影
 * @date 2021/1/18
 */

@Slf4j
@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private ProductFeignService productFeignService;

    @Autowired
    private ThreadPoolExecutor executor;

    private final String CART_PREFIX = "gulimall:cart:";

    /**
     * 将商品添加到购物车
     * @param skuId
     * @param num
     * @throws ExecutionException
     * @throws InterruptedException
     */
    @Override
    public void addCartItem(Long skuId, Integer num) throws ExecutionException, InterruptedException {
        BoundHashOperations<String, Object, Object> cartOps = this.getCartOps();

        String itemJsonString = (String) cartOps.get(skuId.toString());
        if (StringUtils.isEmpty(itemJsonString)) {
            //购物车无此商品,添加新商品到购物车
            CartItem cartItem = new CartItem();

            //1.远程查询当前要添加的商品信息
            CompletableFuture<Void> getSkuInfoTask = CompletableFuture.runAsync(() -> {
                R r = productFeignService.getSkuInfo(skuId);
                SkuInfoVo skuInfoVo = r.getDataByKey("skuInfo", new TypeReference<SkuInfoVo>() {
                });

                cartItem.setCheck(true);
                cartItem.setCount(num);
                cartItem.setImage(skuInfoVo.getSkuDefaultImg());
                cartItem.setTitle(skuInfoVo.getSkuTitle());
                cartItem.setSkuId(skuInfoVo.getSkuId());
                cartItem.setPrice(skuInfoVo.getPrice());

            }, executor);

            //2.远程查询sku的组合信息
            CompletableFuture<Void> getSkuSaleAttrValues = CompletableFuture.runAsync(() -> {
                List<String> skuSaleAttrs = productFeignService.getSkuSaleAttrValues(skuId);
                cartItem.setSkuSaleAttrs(skuSaleAttrs);
            }, executor);

            CompletableFuture.allOf(getSkuInfoTask, getSkuSaleAttrValues).get();

            String jsonString = JSON.toJSONString(cartItem);
            cartOps.put(skuId.toString(), jsonString);

        } else {
            //购物车有此商品,修改数量即可
            CartItem cartItem = JSON.parseObject(itemJsonString, CartItem.class);
            cartItem.setCount(cartItem.getCount() + num);

            String jsonString = JSON.toJSONString(cartItem);
            cartOps.put(skuId.toString(), jsonString);
        }

    }

    /**
     * 根据skuId获取购物项
     * @param skuId
     * @return
     */
    @Override
    public CartItem getCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String itemJsonString = (String) cartOps.get(skuId.toString());
        CartItem cartItem = JSON.parseObject(itemJsonString, CartItem.class);
        return cartItem;
    }

    /**
     * 获取当前用户的购物车
     * @return
     * @throws ExecutionException
     * @throws InterruptedException
     */
    @Override
    public Cart getCart() throws ExecutionException, InterruptedException {

        Cart cart = new Cart();

        UserInfoTo userInfoTo = CartInterceptor.userInfoToThreadLocal.get();
        if (userInfoTo.getUserId() != null) {
            //已登录
            String cartKey = CART_PREFIX + userInfoTo.getUserId();
            //如果临时购物车有数据,就要先合并,然后清空临时购物车
            String tempCartKey = CART_PREFIX + userInfoTo.getUserKey();
            List<CartItem> tempCartItems = this.getCartItems(tempCartKey);
            if (!CollectionUtils.isEmpty(tempCartItems)) {
                //临时购物车有数据,需要合并
                for (CartItem cartItem : tempCartItems) {
                    this.addCartItem(cartItem.getSkuId(), cartItem.getCount());
                }
                //清除临时购物车的数据
                this.clearCart(tempCartKey);
            }
            //获取合并后的购物车的数据
            List<CartItem> items = this.getCartItems(cartKey);
            cart.setItems(items);

        } else {
            //未登录
            String cartKey = CART_PREFIX + userInfoTo.getUserKey();
            //获取临时购物车的所有购物项
            List<CartItem> items = this.getCartItems(cartKey);
            cart.setItems(items);
        }

        return cart;
    }

    /**
     * 清空购物车数据
     *
     * @param cartKey
     */
    @Override
    public void clearCart(String cartKey) {
        this.stringRedisTemplate.delete(cartKey);
    }

    /**
     * 勾选购物项
     * @param skuId
     * @param check
     */
    @Override
    public void checkItem(Long skuId, Integer check) {
        BoundHashOperations<String, Object, Object> cartOps = this.getCartOps();
        CartItem cartItem = this.getCartItem(skuId);
        cartItem.setCheck(check == 1 ? true : false);
        String jsonString = JSON.toJSONString(cartItem);
        cartOps.put(skuId.toString(), jsonString);
    }

    /**
     * 修改购物项数量
     *
     * @param skuId
     * @param num
     */
    @Override
    public void changeItemCount(Long skuId, Integer num) {
        CartItem cartItem = this.getCartItem(skuId);
        cartItem.setCount(num);

        BoundHashOperations<String, Object, Object> cartOps = this.getCartOps();
        cartOps.put(skuId.toString(), JSON.toJSONString(cartItem));
    }

    /**
     * 根据skuId删除购物项
     * @param skuId
     */
    @Override
    public void deleteItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = this.getCartOps();
        cartOps.delete(skuId.toString());
    }

    /**
     * 获取购物车中所有被选中的购物项
     * @return
     */
    @Override
    public List<CartItem> getUserCartSelectItems() {
        UserInfoTo userInfoTo = CartInterceptor.userInfoToThreadLocal.get();
        if (userInfoTo.getUserId() == null) {
            return null;
        } else {
            String cartKey = CART_PREFIX + userInfoTo.getUserId();
            List<CartItem> cartItems = this.getCartItems(cartKey);

            //获取所有被选中的购物项
            List<CartItem> collect = cartItems
                    .stream()
                    .filter(cartItem -> cartItem.getCheck())
                    .map(cartItem -> {
                        //获取最新的价格
                        R r = this.productFeignService.getPrice(cartItem.getSkuId());
                        BigDecimal price = r.getData(new TypeReference<BigDecimal>() {
                        });
                        cartItem.setPrice(price);
                        return cartItem;
                    })
                    .collect(Collectors.toList());

            return collect;
        }
    }

    /**
     * 根据登录状态,获取我们要操作的购物车
     *
     * @return
     */
    private BoundHashOperations<String, Object, Object> getCartOps() {
        UserInfoTo userInfoTo = CartInterceptor.userInfoToThreadLocal.get();
        String cartKey = "";
        if (userInfoTo.getUserId() != null) {
            cartKey = CART_PREFIX + userInfoTo.getUserId();
        } else {
            cartKey = CART_PREFIX + userInfoTo.getUserKey();
        }

        BoundHashOperations<String, Object, Object> operations = stringRedisTemplate.boundHashOps(cartKey);
        return operations;

    }

    /**
     * 获取购物车数据
     *
     * @param cartKey
     * @return
     */
    private List<CartItem> getCartItems(String cartKey) {
        BoundHashOperations<String, Object, Object> hashOps = stringRedisTemplate.boundHashOps(cartKey);
        List<Object> values = hashOps.values();
        if (!CollectionUtils.isEmpty(values)) {
            List<CartItem> items = values.stream().map((obj) -> {
                String jsonString = obj.toString();
                CartItem cartItem = JSON.parseObject(jsonString, CartItem.class);
                return cartItem;
            }).collect(Collectors.toList());
            return items;
        }
        return null;
    }

}
